package net.xiaohanlin.smartmetric.config;

import java.io.File;
import java.net.URL;

public class SmartMetricConfigService {

	private SmartMetricConfiguration smartMetricsConfiguration;
	public static SmartMetricConfigService instance = new SmartMetricConfigService();

	private SmartMetricConfigService() {

	}

	public SmartMetricConfiguration readConfigurations(String fileName) {
		File configFile = locateFile(fileName);
		if (fileName.toLowerCase().endsWith("xml")) {
			SmartMetricConfigXmlReader smartMetricsConfigXmlReader = new SmartMetricConfigXmlReader(configFile);
			this.smartMetricsConfiguration = smartMetricsConfigXmlReader.readConfiguration();
		}
		return smartMetricsConfiguration;
	}

	public SmartMetricConfiguration getSmartMetricConfiguration() {
		return smartMetricsConfiguration;
	}

	private File locateFile(String fileName) {
		if (fileName == null) {
			throw new ExceptionInInitializerError("config file name is null , " + fileName);
		}

		File file = new File(fileName);
		if (!file.exists()) {// 不存在的话需要重新定位文件
			// 先从class去读
			URL resource = this.getClass().getResource(fileName);
			if (resource == null) {
				resource = this.getClass().getClassLoader().getResource(fileName);
			}

			if (resource == null) {
				throw new ExceptionInInitializerError("cannot findout resource : " + fileName);
			}
			file = new File(resource.getFile());
		}
		return file;
	}

}
